<!-- view/users/users/index.vue -->
<template>
  <el-card class="box-card">
    <el-form ref="form" :model="form" inline>
      <el-form-item prop="search">
        <el-input v-model="form.search" clearable style="width: 200px" prefix-icon="search" placeholder="输入名称" />
      </el-form-item>

      <el-form-item>
        <el-button type="success" icon="search" size="small" @click="search(form)">搜索</el-button>
      </el-form-item>
    </el-form>

    <el-button type="primary" style="margin-bottom: 20px" icon="Edit" size="small" @click="createUser()">新增</el-button>

    <!--表单组件-->
    <el-table ref="table" :data="tableData" style="width: 100%" row-key="id" :header-cell-style="{ background: '#fafafa', color: '#606266' }" highlight-current-row>
      <el-table-column prop="username" label="用户名" min-width="100" show-overflow-tooltip />

      <el-table-column prop="name" label="姓名" min-width="100" show-overflow-tooltip />

      <el-table-column prop="position" label="职位" min-width="100" show-overflow-tooltip />
      <el-table-column prop="email" label="用户邮箱" min-width="100" show-overflow-tooltip />

      <!-- <el-table-column label="状态" align="center" width="100">
        <template #default="scope">
          <el-switch v-model="scope.row.is_active" :disabled="!checkPermission(['admin', 'user-users-lock']) || scope.row.id === userId" :active-value="true" :inactive-value="false" active-color="#13ce66" inactive-color="#ff4949" @change="changeIsActive($event, scope.row)" />
        </template>
      </el-table-column> -->

          <el-table-column
                label="状态"
                align="center"
                width="100"
              >
              
                <template  #default="scope">
                  <!-- v-model="row.is_active" -->
                  <el-switch
                    v-model="scope.row.is_active"
                    :disabled="!checkPermission(['admin', 'user-users-lock']) || scope.row.id === userId"
                    :active-value="true"
                    :inactive-value="false"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    @change="changeIsActive($event, scope.row)"
                  />
                </template>
              </el-table-column>

      <el-table-column fixed="right" align="center" label="操作" width="220">
        <template #default="scope">
          <el-button type="primary" icon="edit" size="small" @click="updateUser(scope.row)"></el-button>
          <el-button type="danger" icon="delete" size="small" @click="deleteUser(scope.row)"></el-button>

          <el-tooltip content="用户权限" placement="top">
            <el-button type="warning" icon="user" size="small" @click="userPermissions(scope.row)"></el-button>
          </el-tooltip>

          <el-tooltip content="重置密码" placement="top">
            <el-button type="warning" icon="lock" size="small" @click="resetPass(scope.row)"> </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!--分页组件-->
    <el-pagination background :current-page="currentPage" :page-sizes="pagesizeList" :page-size="pagesize" :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    <cuForm :dialog-visible="cuDialogVisible" :cur-id="curId" @close="close" @search="search" />
    <resetPwdForm :reset-pass-dialog-visible="resetPassDialogVisible" :cur-id="curId" @close="close" />
    <permissionsDialog :permissions-dialog-visible="permissionsDialogVisible" :cur-id="curId"  @close="close" />

  </el-card>
</template>
<script>
import checkPermission from '@/utils/permission'
import cuForm from './components/cuForm.vue'
import resetPwdForm from './components/resetPwdForm.vue'
import permissionsDialog from './components/permissionsDialog.vue'
import { deleteUser, getUsers, updateUserActive } from "@/api/user/users";

export default {
  name: "User-User",
  components: {
    cuForm,
    resetPwdForm, // 注册 resetPwdForm 组件
    permissionsDialog, // 注册 permissionsDialog 组件
  },

  data () {
    return {
      currentPage: 1, // 当前页面
      pagesize: 10,  // 默认每页的数据条数
      pagesizeList: [10, 20, 50, 100], // 当前分页数
      total: 0,  // 总数据条数
      form: {
        page: 1,
        size: 10,
        search: "",
        ordering: "",
      },
      userId: null,
      tableData: [],
      isAllSelect: false,
      multipleSelection: [],
      // cuForm数据
      cuDialogVisible: false,
      curId: null,
      resetPassDialogVisible: false,
      permissionsDialogVisible: false,
    };
  },
  created () {
    this.search();
  },
  mounted () {
    console.log("打印变量:$store.state", this.$store.state);
    console.log("打印变量:getUserPermissions", this.getUserPermissions);
  },
  methods: {
    checkPermission,
    resetPass(row) {
      this.resetPassDialogVisible = true
      this.curId = row.id
    console.log("this.curId +++++", this.curId);
    },

    // 用户权限组件
    userPermissions(row) {
      this.permissionsDialogVisible = true
      this.curId = row.id
        console.log("this.curId +++++", this.curId);
    },
    // 获取列表/搜索功能
    search () {
      getUsers(this.form).then((response) => {
        this.tableData = response.data.results;
        this.total = response.data.count;
        console.log("当前total数量:", this.total);
      });
    },
    // 重置
    resetForm () {
      this.$refs.form.resetFields();
      this.search();
    },
    // 修改用户状态
    changeIsActive (event, row) {
    console.log('Row:', row);
      const message = !event ? '锁定' : '激活'
      this.$confirm('此操作将' + message + '用户 "' + row.username + '" , 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = { 'is_active': row.is_active }
        updateUserActive(row.id, data).then(res => {
          this.$message({
            message: message + row.username + '成功',
            type: 'success'
          })
        }).catch(() => {
          row.is_active = !row.is_active
        })
      }).catch(() => {
        row.is_active = !row.is_active
      })
    },

    // 删除
    deleteUser (row) {
      row.isHighlighted = true; // 在数据对象中添加一个属性用于标记是否应用样式
      this.$confirm('此操作将删除"' + row.username + '" , 是否继续？', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteUser(row.id).then((response) => {
          if (response.status == 204) {
            this.$message.success("删除成功");
            this.search(); // 刷新table
          } else {
            this.$message.error(response);
          }
        });
      }).catch(() => {
        // 异常处理
        console.error("取消删除操作");
      });
    },

    // cuForm子组件
    createUser () {
      this.cuDialogVisible = true;
    },
    updateUser (row) {
      this.curId = row.id;
      this.cuDialogVisible = true;
    },
    close () {
      this.cuDialogVisible = false;
      this.resetPassDialogVisible = false;
      this.permissionsDialogVisible = false;
      this.curId = null;
    },
    //页面大小发生变化时触发，赋值并重新获取列表
    handleSizeChange (pagesize) {
      this.pagesize = pagesize  // 重新设置分页显示
      this.form.size = pagesize // 将最新值更新到表单里
      this.search();
    },
    //页数发生变化时触发，复制并重新获取列表
    handleCurrentChange (currentPage) {
      this.currentPage = currentPage;
      this.form.page = currentPage;
      this.search();
    },
  },
};
</script>

<style>
.delete-username {
  color: red;
}
</style>